﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace PF_Drive
{
    public static class PF_Tools
    {
        public static Encoding GetEncoding(string EncodingName)
        {
            switch (EncodingName.ToUpper())
            {
                case "ASCII":
                    return Encoding.ASCII;
                case "DEFAULT":
                    return Encoding.Default;
                case "UNICODE":
                    return Encoding.Unicode;
                case "UTF32":
                    return Encoding.UTF32;
                case "UTF7":
                    return Encoding.UTF7;
                case "UTF8":
                    return Encoding.UTF8;
                case "GBK":
                    return Encoding.GetEncoding("GBK");
                case "GB2312":
                    return Encoding.GetEncoding("GB2312");
                case "GB18030":
                    return Encoding.GetEncoding("GB18030");
            }
            return Encoding.UTF8;
        }

        /// <summary>
        /// 串口实例对象
        /// </summary>
        public struct COMSettings
        {
            /// <summary>
            /// 串口号
            /// </summary>
            public int com;
            /// <summary>
            /// 波特率
            /// </summary>
            public int baud;                 //波特率，值只能为2400,4800,9600 ,115200
                                             /// <summary>
                                             /// 数据位
                                             /// </summary>
            public int databits;             //数据位，只能是7,8
                                             /// <summary>
                                             /// 效验位
                                             /// None、Even、Mark、Odd、Space
                                             /// </summary>
            public Parity parity;              //校验位，’N’无，’O’奇数位，’E’偶数位
                                               /// <summary>
                                               /// 停止位
                                               /// None、One、OnePointFive、Two
                                               /// </summary>
            public StopBits stopbits;          //停止位，只能是1,2
                                               /// <summary>
                                               /// 字符串编码格式
                                               /// </summary>
            public Encoding encode;
        }

        /// <summary>
        /// 串口通讯效验位
        /// </summary>
        /// <param name="parity"></param>
        /// <returns></returns>
        public static Parity COMParity(string parity)
        {
            switch (parity.ToUpper())
            {
                case "N": return Parity.None;
                case "E": return Parity.Even;
                case "M": return Parity.Mark;
                case "0": return Parity.Odd;
                case "S": return Parity.Space;
            }
            return Parity.None;
        }

        /// <summary>
        /// 串口通讯停止位
        /// </summary>
        /// <param name="stopBits"></param>
        /// <returns></returns>
        public static StopBits COMStopBits(string stopBits)
        {
            switch (stopBits.ToUpper())
            {
                // case "NONE": return  StopBits.None;
                case "ONE": return StopBits.One;
                case "ONEPOINTFIVE": return StopBits.OnePointFive;
                case "TWO": return StopBits.Two;
            }
            return StopBits.One;
        }

        public static string HexToStrUTF32(byte[] data, Encoding encode)
        {
            byte[] byt = new byte[data.Length / 2];
            string mm = string.Empty;
            for (int i = 0; i < data.Length; i += 2)
            {
                mm += Char.ConvertFromUtf32(data[i]);
                mm += Char.ConvertFromUtf32(data[i + 1]);
                if (!byte.TryParse(mm, NumberStyles.HexNumber, null, out byt[i / 2]))
                    byt[i / 2] = 0;
                mm = string.Empty;
            }
            return encode.GetString(byt);
        }

        public static string HexToStr(string mHex, Encoding encode) // 返回十六进制代表的字符串 
        {
            mHex = mHex.Replace(" ", "");
            if (mHex.Length <= 0) return "";
            byte[] vBytes = new byte[mHex.Length / 2];
            for (int i = 0; i < mHex.Length; i += 2)
                if (!byte.TryParse(mHex.Substring(i, 2), NumberStyles.HexNumber, null, out vBytes[i / 2]))
                    vBytes[i / 2] = 0;
            return encode.GetString(vBytes);
        }


        #region 判断对象是否为空
        /// <summary>
        /// 判断对象是否为空，为空返回true
        /// </summary>
        /// <typeparam name="T">要验证的对象的类型</typeparam>
        /// <param name="data">要验证的对象</param>        
        public static bool IsNullOrEmpty<T>(T data)
        {
            if (data == null)
            {
                return true;
            }

            if (data is string)
            {
                if (String.IsNullOrEmpty(data.ToString().Trim()))
                {
                    return true;
                }
            }

            return data is DBNull;
        }

        /// <summary>
        /// 判断对象是否为空，为空返回true
        /// </summary>
        /// <param name="data">要验证的对象</param>
        public static bool IsNullOrEmpty(object data)
        {
            if (data == null)
            {
                return true;
            }

            if (data is string)
            {
                if (String.IsNullOrEmpty(data.ToString().Trim()))
                {
                    return true;
                }
            }

            return data is DBNull;
        }
        #endregion

        #region 验证IP地址是否合法
        /// <summary>
        /// 验证IP地址是否合法
        /// </summary>
        /// <param name="ip">要验证的IP地址</param>        
        public static bool IsIp(string ip)
        {
            if (IsNullOrEmpty(ip))
            {
                return false;
            }

            ip = ip.Trim();

            const string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";

            return Regex.IsMatch(ip, pattern);
        }
        #endregion

        #region  验证EMail是否合法
        /// <summary>
        /// 验证EMail是否合法
        /// </summary>
        /// <param name="email">要验证的Email</param>
        public static bool IsEmail(string email)
        {
            if (IsNullOrEmpty(email))
            {
                return false;
            }

            email = email.Trim();

            const string pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$";

            return Regex.IsMatch(email, pattern);
        }
        #endregion

        #region 验证是否为整数
        /// <summary>
        /// 验证是否为整数 如果为空，认为验证不合格 返回false
        /// </summary>
        /// <param name="number">要验证的整数</param>        
        public static bool IsInt(string number)
        {
            if (string.IsNullOrEmpty(number))
            {
                return false;
            }
            number = number.Trim();
            int output;
            return int.TryParse(number, out output);
        }
        #endregion

        #region 验证是否为数字
        /// <summary>
        /// 验证是否为数字
        /// </summary>
        /// <param name="number">要验证的数字</param>        
        public static bool IsNumber(string number)
        {
            if (IsNullOrEmpty(number))
            {
                return false;
            }

            number = number.Trim();

            const string pattern = @"^[0-9]+[0-9]*[.]?[0-9]*$";

            return Regex.IsMatch(number, pattern);
        }
        #endregion

        #region 验证日期是否合法
        /// <summary>
        /// 验证日期是否合法,对不规则的作了简单处理
        /// </summary>
        /// <param name="date">日期</param>
        public static bool IsDate(ref string date)
        {
            if (IsNullOrEmpty(date))
            {
                return true;
            }

            date = date.Trim();

            date = date.Replace(@"\", "-");
            date = date.Replace(@"/", "-");

            if (date.IndexOf("今", StringComparison.Ordinal) != -1)
            {
                date = DateTime.Now.ToString();
            }

            try
            {
                //用转换测试是否为规则的日期字符
                date = Convert.ToDateTime(date).ToString("d");
                return true;
            }
            catch
            {
                //如果日期字符串中存在非数字，则返回false
                if (!IsInt(date))
                {
                    return false;
                }

                #region 对纯数字进行解析
                //对8位纯数字进行解析
                if (date.Length == 8)
                {
                    //获取年月日
                    string year = date.Substring(0, 4);
                    string month = date.Substring(4, 2);
                    string day = date.Substring(6, 2);

                    //验证合法性
                    if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                    {
                        return false;
                    }
                    if (Convert.ToInt32(month) > 12 || Convert.ToInt32(day) > 31)
                    {
                        return false;
                    }

                    //拼接日期
                    date = Convert.ToDateTime(year + "-" + month + "-" + day).ToString("d");
                    return true;
                }

                //对6位纯数字进行解析
                if (date.Length == 6)
                {
                    //获取年月
                    string year = date.Substring(0, 4);
                    string month = date.Substring(4, 2);

                    //验证合法性
                    if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                    {
                        return false;
                    }
                    if (Convert.ToInt32(month) > 12)
                    {
                        return false;
                    }

                    //拼接日期
                    date = Convert.ToDateTime(year + "-" + month).ToString("d");
                    return true;
                }

                //对5位纯数字进行解析
                if (date.Length == 5)
                {
                    //获取年月
                    string year = date.Substring(0, 4);
                    string month = date.Substring(4, 1);

                    //验证合法性
                    if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                    {
                        return false;
                    }

                    //拼接日期
                    date = year + "-" + month;
                    return true;
                }

                //对4位纯数字进行解析
                if (date.Length == 4)
                {
                    //获取年
                    string year = date.Substring(0, 4);

                    //验证合法性
                    if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                    {
                        return false;
                    }

                    //拼接日期
                    date = Convert.ToDateTime(year).ToString("d");
                    return true;
                }
                #endregion

                return false;
            }
        }
        #endregion

        #region 验证身份证是否合法
        /// <summary>
        /// 验证身份证是否合法
        /// </summary>
        /// <param name="idCard">要验证的身份证</param>        
        public static bool IsIdCard(string idCard)
        {
            if (IsNullOrEmpty(idCard))
            {
                return true;
            }

            idCard = idCard.Trim();

            var pattern = new StringBuilder();
            pattern.Append(@"^(11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|");
            pattern.Append(@"50|51|52|53|54|61|62|63|64|65|71|81|82|91)");
            pattern.Append(@"(\d{13}|\d{15}[\dx])$");

            return Regex.IsMatch(idCard, pattern.ToString());
        }
        #endregion

        #region 检测客户的输入中是否有危险字符串
        /// <summary>
        /// 检测客户输入的字符串是否有效,并将原始字符串修改为有效字符串或空字符串。
        /// 当检测到客户的输入中有攻击性危险字符串,则返回false,有效返回true。
        /// </summary>
        /// <param name="input">要检测的字符串</param>
        public static bool IsValidInput(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return false;
            }
            var testChars = new[] { ',', ';', '\'', '"', '-' };

            foreach (var testStr in testChars)
            {
                if (input.ToLower().Contains(testStr.ToString())) return false;
            }

            //检测攻击性危险字符串
            const string testString = "and |or |exec |insert |select |delete |update |count |chr |mid |master |truncate |char |declare";
            var testArray = testString.Split('|');
            foreach (var testStr in testArray)
            {
                if (input.ToLower().Contains(testStr)) return false;
            }

            return true;
        }
        #endregion
    }
}
